﻿using Microsoft.Reporting.WebForms;
using pbvs.Data;
using pbvs.Data.Repositories.Interfaces;
using pbvs.Models.ViewModels;
using System;
using System.Collections.Generic;
using pbvs.Data.Repositories.RepositoryExtensions;
using System.Web;
using pbvs.Services.Interfaces;
using pbvs.Services.ServiceExtensions;

namespace pbvs.Services
{
    public class ReportService : IReportService
    {
        private readonly IValuationRepository _db;
        private readonly ReportViewer _rv;
		private readonly VariablesFull _vars;
		protected IEnumerable<ValuationReport> Valuations { get; set; }


        public ReportService(IValuationRepository db, VariablesFull vars)
        {
            _db = db;
			_vars = vars;
            _rv = new ReportViewer();
            _rv.LocalReport.ReportPath = "Reports/pbvs.rdlc";
        }

        public void RequestReport(int id)
        {
            Valuations = _db.Valuations.ById(id).ToValuationReports(_vars);
            GenerateReport();
        }

        private void GenerateReport()
        {
            _rv.LocalReport.DataSources.Add(new ReportDataSource("dsValuation", Valuations));
            _rv.LocalReport.Refresh();
            RenderPdf();
        }

        private void RenderPdf()
        {
            const string reportType = "PDF";
            string mimeType;
            string encoding;
            string[] streams;
            string extension = "PDF";
            Warning[] warnings;
            const string deviceInfo = "<DeviceInfo><OutputFormat>PDF</OutputFormat><PageWidth>8.5in</PageWidth><PageHeight>11in</PageHeight></DeviceInfo>";
            var renderedBytes = _rv.LocalReport.Render(reportType, deviceInfo, out mimeType, out encoding,
                                                      out extension, out streams, out warnings);

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = mimeType;
            HttpContext.Current.Response.AddHeader("content-disposition",
                                                              String.Format("inline; filename={0}.pdf", Guid.NewGuid().ToString()));
            HttpContext.Current.Response.BinaryWrite(renderedBytes);
            HttpContext.Current.Response.End();
        }
    }
}
